package utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.Flucard_IT.R;
import com.Flucard_IT.SplashScreen;

public class Utils {

	private static AlertDialog mAdConnection = null;
	private Context context;
	private static Handler mHandler = new Handler();
	private ProgressDialog mPdWaiting = null;

	public Utils(Context context) {
		setContext(context);
	}

	public Context getContext() {
		return context;
	}

	public void setContext(Context context) {
		this.context = context;
	}

	/**
	 * Check fill blank
	 */
	public static boolean checkFillBlank(EditText et) {
		if (et.getText().toString().equals("")) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Check fill password characters At least 8 characters
	 */
	public static boolean checkFillPassword(EditText et) {
		if (et.getText().toString().length() >= 8) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Get current date
	 */
	public static String getCurrentDate() {
		Calendar c = Calendar.getInstance();

		SimpleDateFormat df = new SimpleDateFormat("dd MMM");
		String formattedDate = df.format(c.getTime());

		return formattedDate;
	}

	/**
	 * Get Float format with 4 digits
	 */
	public static String getFloatFormat(float value) {
		return String.format("%.4f", value);
	}

	/**
	 * Get current date
	 */
	public static long getLastDaysInMilliseconds(int number_of_date) {
		Date today = new Date();

		Calendar cal = new GregorianCalendar();
		cal.setTime(today);

		if (number_of_date != 0) {
			cal.add(Calendar.DAY_OF_MONTH, -number_of_date);
		}

		return cal.getTimeInMillis() / 1000;
	}

	/**
	 * Hide alert connection dialog
	 */
	public static void hideConnectionDialog() {
		mHandler.post(new Runnable() {

			@Override
			public void run() {
				mAdConnection.dismiss();
			}
		});
	}

	/**
	 * Hide progress dialog
	 */
	public void hideProgressDialog() {
		if (mPdWaiting != null && mPdWaiting.isShowing()) {
			mPdWaiting.dismiss();
			mPdWaiting = null;
		}
	}

	/**
	 * Hidden keyboard
	 */
	public void hideSoftKeyboard() {
		try {
			InputMethodManager mImm = (InputMethodManager) context
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			mImm.hideSoftInputFromWindow(((Activity) context).getCurrentFocus()
					.getWindowToken(), 0);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void hideSoftKeyboard(Activity activity) {
		activity.getWindow().setSoftInputMode(InputMethodManager.RESULT_HIDDEN);
	}

	public void hideSoftKeyboard(EditText et) {
		InputMethodManager imm = (InputMethodManager) context
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
		imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
	}

	/**
	 * Initial data for full screen dialog
	 */
	public void initialFullScreenDialog(Dialog dialog) {
		// Initial layout for dialog
		WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
		lp.copyFrom(dialog.getWindow().getAttributes());
		lp.width = LayoutParams.MATCH_PARENT;
		lp.height = LayoutParams.MATCH_PARENT;

		dialog.getWindow().setAttributes(lp);

	}

	/**
	 * Initialize alert connection dialog
	 */
	public static void initialConnectionDialog(final Context context) {
		mHandler.post(new Runnable() {

			@Override
			public void run() {
				mAdConnection = new AlertDialog.Builder(context).create();
				mAdConnection.setTitle(context
						.getString(R.string.title_failed_connection));
				mAdConnection.setIcon(R.drawable.ibtn_error_dismiss);
				mAdConnection.setCancelable(false);
				mAdConnection.setMessage(context
						.getString(R.string.content_failed_server_connection));
				mAdConnection.setButton(DialogInterface.BUTTON_POSITIVE,
						context.getString(R.string.try_again),
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog9,
									int whichButton) {
								hideConnectionDialog();

								// New intent to wireless setting
								context.startActivity(new Intent(
										android.provider.Settings.ACTION_WIRELESS_SETTINGS));
							}
						});
				mAdConnection.setButton(DialogInterface.BUTTON_NEGATIVE,
						context.getString(R.string.quit),
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog9,
									int whichButton) {
								android.os.Process
										.killProcess(android.os.Process.myPid());
							}
						});
			}
		});
	}

	/**
	 * Is App already installed or not
	 */
	public boolean isAppInstalled(String packageName) {
		if (context != null) {
			PackageManager pm = context.getPackageManager();
			boolean installed = false;
			try {
				pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
				installed = true;
			} catch (PackageManager.NameNotFoundException e) {
				installed = false;
			}

			return installed;
		}

		return false;
	}

	/**
	 * Check network connection
	 */
	public boolean isNetworkOnline() {
		boolean status = false;
		try {
			ConnectivityManager cm = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo netInfo = cm.getNetworkInfo(0);
			if (netInfo != null
					&& netInfo.getState() == NetworkInfo.State.CONNECTED) {
				status = true;
			} else {
				netInfo = cm.getNetworkInfo(1);
				if (netInfo != null
						&& netInfo.getState() == NetworkInfo.State.CONNECTED)
					status = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return status;
	}

	/**
	 * Restart application immediately
	 */
	public static void restartApplication(Context source, Context destination) {
		// Restart the application by using the way : Set alarm timer to
		// open the application again in a few seconds will be the better way
		PendingIntent mPi = PendingIntent.getActivity(source, 0, new Intent(
				new Intent(source, SplashScreen.class)), ((Activity) source)
				.getIntent().getFlags());
		AlarmManager mgr = (AlarmManager) ((Activity) source)
				.getSystemService(Context.ALARM_SERVICE);
		mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, mPi);
	}

	/**
	 * Remove view parent
	 */
	public static void removeViewParent(View v) {
		((ViewGroup) v.getParent()).removeView(v);
	}

	/**
	 * Hide alert connection dialog
	 */
	public static void showConnectionDialog() {
		mHandler.post(new Runnable() {

			@Override
			public void run() {
				mAdConnection.show();
			}
		});
	}

	/**
	 * show connection timeout dialog
	 */
	public void showConnectionTimeoutDialog(final Context context,
			final Class<?> object) {
		mAdConnection = new AlertDialog.Builder(context).create();
		mAdConnection.setTitle(context
				.getString(R.string.title_failed_connection));
		mAdConnection.setIcon(R.drawable.ibtn_error_dismiss);
		mAdConnection.setCancelable(false);
		mAdConnection.setMessage(context
				.getString(R.string.content_failed_server_connection));
		mAdConnection.setButton(DialogInterface.BUTTON_POSITIVE,
				context.getString(R.string.try_again),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog9, int whichButton) {
						((Activity) context).finish();
						context.startActivity(new Intent(context, object));
					}
				});
		mAdConnection.setButton(DialogInterface.BUTTON_NEGATIVE,
				context.getString(R.string.quit),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog9, int whichButton) {
						android.os.Process.killProcess(android.os.Process
								.myPid());
					}
				});
		mAdConnection.show();
	}

	/**
	 * Show progress dialog
	 */
	public void showProgressDialog() {
		if (mPdWaiting == null) {
			mPdWaiting = ProgressDialog.show(context,
					context.getString(R.string.title_loading),
					context.getString(R.string.content_loading));
		}
	}

	/**
	 * Show progress dialog
	 */
	public void showToast(String text) {
		Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
	}
}
